<!DOCTYPE html>
<title>Test autoplay is allowed if the document is capturing</title>
<script src='../../resources/testharness.js'></script>
<script src='../../resources/testharnessreport.js'></script>
<body></body>
<script>

function testAutoplay() {
  const video = document.createElement('video');
  video.src = '../content/test.ogv';

  return new Promise((resolve) => {
    video.play().then(() => resolve(true),
      (e) => resolve(e.name != 'NotAllowedError'));
  });
}

async_test(t => {
  t.add_cleanup(() => {
    internals.settings.setAutoplayPolicy('no-user-gesture-required');
  });

  internals.settings.setAutoplayPolicy('document-user-activation-required');

  /* The capturing video element */
  let capturingVideo  = document.createElement('video');

  testAutoplay().then(t.step_func((success) => {
    // We should not be able to autoplay without a user gesture.
    assert_false(success);

    // Start capturing user media.
    navigator.mediaDevices.getUserMedia({video: true}).then(
      t.step_func(step2), t.unreached_func());
  }));

  function step2(stream) {
    capturingVideo.srcObject = stream;
    capturingVideo.play().then(t.step_func(step3), t.unreached_func());
  }

  function step3() {
    testAutoplay().then(t.step_func((success) => {
      // Autoplay should be enabled as we are capturing.
      assert_true(success);

      capturingVideo.srcObject.getTracks()[0].stop();

      testAutoplay().then(t.step_func_done((success) => {
        // Autoplay should be disabled again.
        assert_false(success);
      }));
    }));
  }
});

</script>
